package com.cloudcc.mobile.view.web;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MotionEvent;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.MenuToggleEvent;
import com.cloudcc.cloudframe.bus.StartWebEvent;
import com.cloudcc.cloudframe.util.DensityUtils;
import com.cloudcc.cloudframe.util.SharePreferece;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.dialog.CallLogLoadingDialog;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.util.DialogUtils;
import com.cloudcc.mobile.util.DialogUtils.OnDoClickListener;
import com.cloudcc.mobile.util.NetWork;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.weight.CustomProgressDialog;
import com.cloudcc.mobile.weight.ui.PullToRefreshWebView;

/**
 * @Description: webview的基类
 * @author wangzhiqiang
 * @date 2015-11-10 上午10:20:08
 * 
 */
public class BaseWebActivity extends BaseActivity {

	public static final String ARG_PLANET_NUMBER = "planet_number";
	public static final int OPEN_RESULT = 1;
	public static final int PINK_RESULT = 2;
	/**
	 * webview
	 */
	protected WebView mWebView;
	protected ImageView back;
	protected ImageView refresh;
	protected RelativeLayout ctrl_container;
	protected PullToRefreshWebView mRefresh;

	protected CallLogLoadingDialog mProgress;
	private boolean _isVisible;// 控制bindtoken影响的问题
	protected SharePreferece mShare;
	protected NetWork mNetWork;
	protected ValueCallback<Uri> mUploadMessage;

	protected String mUrl = StringUtils.EMPTY;

	/**
	 * 滑动返回
	 */
	private float ux, dx;

	@Override
	public void init(Bundle savedInstanceState) {
		super.init(savedInstanceState);
		// 进度条
		mProgress = new CallLogLoadingDialog(this,R.style.DialogLoadingTheme);
		mShare = new SharePreferece(mContext);
		mNetWork = new NetWork();
		initUI();
		initSetting();
		initClient();

	}

	protected void initUI() {

	}

	protected void initSetting() {

	}

	protected void initClient() {
		mWebView.addJavascriptInterface(new JsInteration(), "cloudcc");
		mWebView.setWebChromeClient(new MyWebChromeClient());
	}

	@Override
	public int getLayoutId() {
		return R.layout.webview2;
	}

	@SuppressLint("SdCardPath")
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == PINK_RESULT) {
			if (null == mUploadMessage)
				return;
			Uri result = intent == null || resultCode != this.RESULT_OK ? null
					: intent.getData();
			mUploadMessage.onReceiveValue(result);
			mUploadMessage = null;
		}
	}

	/**
	 * 重新bin定的时候
	 * 
	 * @param event
	 */
	public void onEventMainThread(StartWebEvent event) {
		if (event.isError()) {
			EventEngine.post(new MenuToggleEvent(false, false));
			this.finish();
			return;
		}
		mWebView.loadUrl(mUrl);
		EventEngine.uregister(this);
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		// 当按下时处理
		if (ev.getAction() == MotionEvent.ACTION_DOWN) {
			dx = ev.getX();
		} else if (ev.getAction() == MotionEvent.ACTION_UP) {// 松开处理
			ux = ev.getX();
			if ((int) (ux - dx) > DensityUtils.getScreenWidth(mContext) / 2
					&& ux > dx) {
				finish();
				// 设置切换动画，从右边进入，左边退出
				overridePendingTransition(R.anim.in_from_left,
						R.anim.out_to_right);
			}
		}
		return super.dispatchTouchEvent(ev);
	}

	/**
	 * 开始显示进度条
	 */
	protected void showProgress() {
		if (_isVisible) {
			if (mProgress == null) {
				mProgress = new CallLogLoadingDialog(this,R.style.DialogLoadingTheme);
				mProgress.show();
				mProgress.settext(getString(R.string.loading));
			}
			if (mProgress != null) {
				mProgress.setCancelable(true);
				mProgress.setCanceledOnTouchOutside(false);
				mProgress.show();
			}
		}
	}

	/**
	 * 停止进度条
	 */
	protected void stopProgress() {
		if (_isVisible && mProgress != null) {
			try {
				mProgress.dismiss();
				mProgress = null;
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	/**
	 * 当前activity的状态
	 * 
	 * @return
	 */
	public boolean isVisible() {
		return _isVisible;
	}

	@Override
	protected void onPause() {
		_isVisible = false;
		hideWaitDialog();
		super.onPause();
	}

	@Override
	protected void onResume() {
		_isVisible = true;
		super.onResume();
	}

	protected class MyWebViewClient extends WebViewClient {

		public void onReceivedSslError(WebView view,
				android.webkit.SslErrorHandler handler,
				android.net.http.SslError error) {
			handler.proceed();
		};

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			AppContext.isError = true;
			String mEn = RunTimeManager.getInstance().getlanguage();
			if ("en".equals(mEn)) {
				view.loadUrl("file:///android_asset/html/en_error.html");
			}else{
			view.loadUrl("file:///android_asset/html/error.html");
			}
		}
	}

	protected class MyWebChromeClient extends WebChromeClient {

		@Override
		public boolean onJsAlert(WebView view, String url, String message,
				final JsResult result) {
			return true;
		}

		@Override
		public boolean onJsConfirm(WebView view, String url, String message,
				final JsResult result) {
			DialogUtils dialogutils = new DialogUtils(mContext);
			dialogutils.showUpdateDialog(mContext, "网页提示", message);
			dialogutils.setOnDoClicktListener(new OnDoClickListener() {
				@Override
				public void confirm() {
					result.confirm();
				}

				@Override
				public void cancel() {
					result.cancel();
				}
			});
			return true;
		}

		public void openFileChooser(ValueCallback<Uri> uploadMsg,
				String acceptType) {
			if (mUploadMessage != null)
				return;
			mUploadMessage = uploadMsg;
			Intent i = new Intent(Intent.ACTION_GET_CONTENT);
			i.addCategory(Intent.CATEGORY_OPENABLE);
			i.setType("*/*");
			startActivityForResult(Intent.createChooser(i, "选择文件"), PINK_RESULT);
		}

		// For Android > 4.1.1
		public void openFileChooser(ValueCallback<Uri> uploadMsg,
				String acceptType, String capture) {
			openFileChooser(uploadMsg, acceptType);
		}

		// For Android < 3.0
		public void openFileChooser(ValueCallback<Uri> uploadMsg) {
			openFileChooser(uploadMsg, "");
		}

	}

	public class JsInteration {

		@JavascriptInterface
		public void back() {
			((Activity) mContext).finish();
		}

		@JavascriptInterface
		public void home() {
			DialogUtils.Exit(mContext);
		}

		@JavascriptInterface
		public void refresh() {
			mWebView.reload();
		}
	}

}
